﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Modeling;

namespace DSLFactory.VSCTDesigner
{
    partial class VSCTDesignerDocData
    {
        protected override void OnDocumentSaving(EventArgs e)
        {
            VSHelper sh = new VSHelper(this.Store);

            if( sh.CanAssignGeneratorTool(this.FileName) )
            {
                CommandTable ct = this.Store.ElementDirectory.FindElements<CommandTable>().FirstOrDefault();
                if( ct != null && String.IsNullOrEmpty(ct.CustomToolGenerator) )
                {
                    CustomToolWizard wizard = new CustomToolWizard();
                    if( wizard.ShowDialog() == System.Windows.Forms.DialogResult.OK )
                    {
                        string customToolName = wizard.CustomToolName;
                        if( String.IsNullOrEmpty(customToolName) )
                        {
                            customToolName = "none";
                        }
                        else
                        {
                            sh.AssignGeneratorTool(this.FileName, wizard.CustomToolName);
                        }

                        using( Transaction transaction = this.Store.TransactionManager.BeginTransaction("Set custom tool name") )
                        {
                            ct.CustomToolGenerator = customToolName;
                            transaction.Commit();
                        }
                    }
                }
            }

            sh.IncrementMenuResource();

            base.OnDocumentSaving(e);
        }
    }
}
